<template>
  <a-modal v-model:open="visible" :title="getModalTitle()" :footer="null" width="400px" @cancel="handleCancel" :maskClosable="false">
    <div class="login-container">
      <!-- 登录表单 -->
      <div v-if="currentView === 'login'">
        <a-form :model="loginForm" layout="vertical" @finish="handleLogin">
          <a-form-item label="账号" name="username" :rules="[{ required: true, message: '请输入账号' }]">
            <a-input v-model:value="loginForm.username" placeholder="请输入账号" />
          </a-form-item>
          <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
            <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" block :loading="loginLoading"> 登录 </a-button>
          </a-form-item>
          <div class="auth-options">
            <a @click="showRegister" class="auth-link">没有账号？立即注册</a>
            <a @click="showForgotPassword" class="auth-link">忘记密码？</a>
          </div>
        </a-form>
      </div>

      <!-- 注册表单 -->
      <div v-else-if="currentView === 'register'">
        <a-form :model="registerForm" layout="vertical" @finish="handleRegister">
          <a-form-item
            label="账号"
            name="username"
            :rules="[
              { required: true, message: '请输入账号' },
              { min: 3, max: 20, message: '账号长度为3-20个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '账号只能包含字母、数字和下划线' }
            ]"
          >
            <a-input v-model:value="registerForm.username" placeholder="请输入账号（3-20个字符）" />
          </a-form-item>
          <a-form-item
            label="邮箱"
            name="email"
            :rules="[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]"
          >
            <a-input v-model:value="registerForm.email" placeholder="请输入邮箱" @blur="onEmailBlur" />
          </a-form-item>
          <a-form-item
            label="邮箱验证码"
            name="verificationCode"
            :rules="[
              { required: true, message: '请输入邮箱验证码' },
              { len: 6, message: '验证码必须是6位数字' },
              { pattern: /^\d{6}$/, message: '验证码只能包含数字' }
            ]"
          >
            <a-input-group compact>
              <a-input v-model:value="registerForm.verificationCode" placeholder="请输入6位验证码" style="width: calc(100% - 120px)" :maxlength="6" />
              <a-button type="primary" style="width: 120px" :disabled="!canSendCode || sendCodeLoading" :loading="sendCodeLoading" @click="handleSendEmailCode">
                {{ codeButtonText }}
              </a-button>
            </a-input-group>
          </a-form-item>
          <a-form-item
            label="密码"
            name="password"
            :rules="[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' }
            ]"
          >
            <a-input-password v-model:value="registerForm.password" placeholder="请输入密码（6-20个字符）" />
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPassword" :rules="[{ required: true, message: '请确认密码' }, { validator: validateConfirmPassword }]">
            <a-input-password v-model:value="registerForm.confirmPassword" placeholder="请再次输入密码" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" block :loading="registerLoading"> 注册 </a-button>
          </a-form-item>
          <div class="auth-options">
            <a @click="showLogin" class="auth-link">已有账号？立即登录</a>
          </div>
        </a-form>
      </div>

      <!-- 忘记密码表单 -->
      <div v-else-if="currentView === 'forgot'">
        <!-- 第一步：输入邮箱发送验证码 -->
        <div v-if="forgotPasswordStep === 1">
          <a-form :model="forgotPasswordForm" layout="vertical" @finish="handleSendResetCode">
            <a-form-item
              label="邮箱"
              name="email"
              :rules="[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入正确的邮箱格式' }
              ]"
            >
              <a-input v-model:value="forgotPasswordForm.email" placeholder="请输入注册时使用的邮箱" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" block :loading="forgotPasswordLoading"> 发送验证码 </a-button>
            </a-form-item>
            <div class="auth-options">
              <a @click="showLogin" class="auth-link">返回登录</a>
            </div>
          </a-form>
        </div>

        <!-- 第二步：输入验证码和新密码 -->
        <div v-else-if="forgotPasswordStep === 2">
          <a-form :model="resetPasswordForm" layout="vertical" @finish="handleResetPassword">
            <a-form-item
              label="验证码"
              name="verificationCode"
              :rules="[
                { required: true, message: '请输入验证码' },
                { len: 6, message: '验证码必须是6位数字' },
                { pattern: /^\d{6}$/, message: '验证码只能包含数字' }
              ]"
            >
              <a-input v-model:value="resetPasswordForm.verificationCode" placeholder="请输入6位验证码" :maxlength="6" />
            </a-form-item>
            <a-form-item
              label="新密码"
              name="newPassword"
              :rules="[
                { required: true, message: '请输入新密码' },
                { min: 6, max: 20, message: '密码长度为6-20个字符' }
              ]"
            >
              <a-input-password v-model:value="resetPasswordForm.newPassword" placeholder="请输入新密码（6-20个字符）" />
            </a-form-item>
            <a-form-item label="确认新密码" name="confirmNewPassword" :rules="[{ required: true, message: '请确认新密码' }, { validator: validateConfirmNewPassword }]">
              <a-input-password v-model:value="resetPasswordForm.confirmNewPassword" placeholder="请再次输入新密码" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" block :loading="resetPasswordLoading"> 重置密码 </a-button>
            </a-form-item>
            <div class="auth-options">
              <a @click="backToSendCode" class="auth-link">重新发送验证码</a>
              <a @click="showLogin" class="auth-link">返回登录</a>
            </div>
          </a-form>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { register, login, sendEmailCode, forgotPassword, resetPassword } from '@/utils/api.js'
import { saveLoginState } from '@/utils/auth.js'
import { useUserStore } from '@/stores/user.js'
import { getEmailCodeManager, EmailCodeManager } from '@/utils/emailCode.js'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'loginSuccess', 'registerSuccess'])

// 使用用户状态管理
const userStore = useUserStore()

// 控制弹窗显示
const visible = ref(props.visible)
const currentView = ref('login')
const loginLoading = ref(false)
const registerLoading = ref(false)
const sendCodeLoading = ref(false)

// 忘记密码相关状态
const forgotPasswordStep = ref(1) // 1: 发送验证码, 2: 重置密码
const forgotPasswordLoading = ref(false)
const resetPasswordLoading = ref(false)

// 邮箱验证码相关状态
const canSendCode = ref(true)
const codeButtonText = ref('获取验证码')
const countdownTimer = ref(null)
const emailCodeManager = ref(null)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: ''
})

// 忘记密码表单
const forgotPasswordForm = reactive({
  email: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  verificationCode: '',
  newPassword: '',
  confirmNewPassword: ''
})

// 监听props变化
watch(
  () => props.visible,
  (newVal) => {
    visible.value = newVal
  }
)

// 监听visible变化
watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// 处理弹窗关闭
const handleCancel = () => {
  visible.value = false
  // 重置表单
  Object.assign(loginForm, { username: '', password: '' })
  Object.assign(registerForm, { username: '', email: '', password: '', confirmPassword: '', verificationCode: '' })
  Object.assign(forgotPasswordForm, { email: '' })
  Object.assign(resetPasswordForm, { verificationCode: '', newPassword: '', confirmNewPassword: '' })
  currentView.value = 'login'
  forgotPasswordStep.value = 1
  // 清理倒计时
  clearCountdown()
}

// 处理登录
const handleLogin = async () => {
  loginLoading.value = true
  try {
    // 调用登录API
    const response = await login({
      username: loginForm.username,
      password: loginForm.password
    })

    // 保存登录状态
    saveLoginState(response.data.token, response.data.user)

    // 更新store中的用户信息
    userStore.setUser(response.data.user)

    message.success('登录成功')
    handleCancel()

    // 触发登录成功事件，通知父组件
    emit('loginSuccess', response.data.user)
  } catch (error) {
    message.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  registerLoading.value = true
  try {
    // 调用注册API
    const response = await register({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      verificationCode: registerForm.verificationCode
    })

    // 保存登录状态（注册成功后自动登录）
    saveLoginState(response.data.token, response.data.user)

    // 更新store中的用户信息
    userStore.setUser(response.data.user)

    message.success('注册成功')
    handleCancel()

    // 触发注册成功事件，通知父组件
    emit('registerSuccess', response.data.user)
  } catch (error) {
    message.error(error.message || '注册失败，请检查输入信息')
  } finally {
    registerLoading.value = false
  }
}

// 验证确认密码
const validateConfirmPassword = (rule, value) => {
  if (value !== registerForm.password) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

// 邮箱输入失焦时，初始化验证码管理器
const onEmailBlur = () => {
  if (registerForm.email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    emailCodeManager.value = getEmailCodeManager(registerForm.email)
    updateCountdownState()
  }
}

// 发送邮箱验证码
const handleSendEmailCode = async () => {
  if (!registerForm.email) {
    message.error('请先输入邮箱地址')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    message.error('请输入正确的邮箱格式')
    return
  }

  if (!emailCodeManager.value?.canSendCode()) {
    message.error('验证码发送太频繁，请稍后再试')
    return
  }

  sendCodeLoading.value = true
  try {
    await sendEmailCode(registerForm.email)
    message.success('验证码已发送，请查收邮箱')

    // 开始倒计时
    emailCodeManager.value.startCountdown()
    startCountdownTimer()
  } catch (error) {
    message.error(error.message || '发送验证码失败')
  } finally {
    sendCodeLoading.value = false
  }
}

// 更新倒计时状态
const updateCountdownState = () => {
  if (!emailCodeManager.value) return

  const remaining = emailCodeManager.value.getRemainingTime()
  canSendCode.value = remaining === 0
  codeButtonText.value = EmailCodeManager.formatTime(remaining)
}

// 开始倒计时定时器
const startCountdownTimer = () => {
  clearCountdown()

  countdownTimer.value = setInterval(() => {
    updateCountdownState()

    if (canSendCode.value) {
      clearCountdown()
    }
  }, 1000)
}

// 清理倒计时
const clearCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

// 组件挂载时检查倒计时状态
onMounted(() => {
  if (registerForm.email) {
    onEmailBlur()
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  clearCountdown()
})

// 显示注册页面
const showRegister = () => {
  currentView.value = 'register'
}

// 显示忘记密码页面
const showForgotPassword = () => {
  currentView.value = 'forgot'
}

// 显示登录页面
const showLogin = () => {
  currentView.value = 'login'
}

// 发送重置密码验证码
const handleSendResetCode = async () => {
  forgotPasswordLoading.value = true
  try {
    await forgotPassword(forgotPasswordForm.email)
    message.success('重置密码验证码已发送，请查收邮箱')
    forgotPasswordStep.value = 2
  } catch (error) {
    message.error(error.message || '发送验证码失败')
  } finally {
    forgotPasswordLoading.value = false
  }
}

// 重置密码
const handleResetPassword = async () => {
  resetPasswordLoading.value = true
  try {
    await resetPassword({
      email: forgotPasswordForm.email,
      verificationCode: resetPasswordForm.verificationCode,
      newPassword: resetPasswordForm.newPassword
    })
    message.success('密码重置成功，请使用新密码登录')
    handleCancel()
    currentView.value = 'login'
  } catch (error) {
    message.error(error.message || '重置密码失败')
  } finally {
    resetPasswordLoading.value = false
  }
}

// 验证确认新密码
const validateConfirmNewPassword = (rule, value) => {
  if (value !== resetPasswordForm.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

// 返回到发送验证码步骤
const backToSendCode = () => {
  forgotPasswordStep.value = 1
  Object.assign(resetPasswordForm, { verificationCode: '', newPassword: '', confirmNewPassword: '' })
}

// 获取模态框标题
const getModalTitle = () => {
  switch (currentView.value) {
    case 'login':
      return '用户登录'
    case 'register':
      return '用户注册'
    case 'forgot':
      return '忘记密码'
    default:
      return '用户登录'
  }
}
</script>

<style scoped>
.login-container {
  padding: 20px 0;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

.auth-options {
  text-align: center;
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
}

.auth-link {
  margin: 0 8px;
  color: #344767;
  font-size: 14px;
}
</style>
